define(function (require) {
    require('bootstrapValidator');
    require('messager');
    require('table');
    require('typeahead');
    require('doctor-data');
    require('fileinput');
    require('daterangepicker');
    require('doctor-select');
    require('moment');
    require('clockpicker');
    require('datetimepicker');
    require('iCheck');
    require('baidueditor');
    window['ZeroClipboard'] = require('zeroclipboard');

    $.module("BASE.airecord", function () {
        var ueditor;

        return {
            init: function () {
                this.loadData();
                this.loadEvent();

                this.initUEditor();
            },
            clearDatas:function () {
                var that = this;

                $("#_id").val(0);
                $("#title").val('');
                $("#searchkey").val('');

                var ue = ueditor;
                ue.setContent("");

                $('#fm').bootstrapValidator('resetForm', true);
                that.showDiv('main_div');
            },
            loadData: function (pageNumber, pageSize) {
                var that = this;

                var s_id = $("#s_id").val();
                var s_title = $("#s_title").val();
                var s_searchkey = $("#s_searchkey").val();
                var s_info = $("#s_info").val();

                SYS.Core.ajax({
                    url: "base/airecord/list",
                    common: {
                        page: pageNumber ? pageNumber : 1,
                        size: pageSize ? pageSize : 20
                    },
                    data: {
                        id: s_id || 0,
                        title: s_title,
                        searchkey: s_searchkey,
                        info: s_info
                    },
                    success: function (data) {
                        var obj = {
                            'pageNumber': data.data.extra.current_page,
                            'pageSize': data.data.extra.page_size,
                            'totalRows': data.data.extra.all_count,
                            'data': data.data.list
                        };

                        $("#myTable").bootstrapTable('destroy');
                        $('#myTable').bootstrapTable({
                            striped: true,
                            singleSelect: false,
                            showColumns: true,
                            showToggle: true,
                            pagination: true,
                            pageNumber: obj.pageNumber,
                            pageSize: obj.pageSize,
                            totalRows: obj.totalRows,
                            pageList: [20, 50, 100, 200],
                            sidePagination: 'server',
                            clickToSelect: true,
                            idField: 'id',
                            data: obj.data,
                            columns: [
                                {field: 'checked', checkbox: true} ,
                                {field: 'id', title: '编号', align: 'center'},
                                {field: 'title', title: '标题', align: 'center'},
                                {field: 'searchkey', title: '关键词', align: 'center'},
                                {
                                    field: 'do', title: '操作', align: 'center',
                                    formatter: function (value, row, index) {
                                        var html = '';
                                        html += '<a href="javascript:void(0)" onclick="BASE.airecord.toEdit(' + row.id + ')" class="btn btn-edit">编辑</a> | ';
                                        html += '<a href="javascript:void(0)" onclick="BASE.airecord.toRemove(' + row.id + ')" class="btn btn-remove  ">删除</a>';
                                        return html;
                                    }
                                }
                            ],
                            onPageChange: function(number, size){
                                that.loadData(number, size);
                            },
                            onRefreshTable: function () {
                                that.loadData();
                            },
                            onClickCell: function (field, value, row, $element) {
                            }
                        });
                    }
                });
            },
            loadEvent: function () {
                var that = this;

                // 定义编辑框form
                var $form = $("#fm");

                // 查询
                $("#search-toolbar").on('click', "#btn_search", function () {
                    that.loadData();
                }).on("keydown ", "input", function (e) {
                    if (e.keyCode == 13) {
                        that.loadData();
                    }
                });

                // 初始化搜索日期控件
                SYS.Tool.initDaterangSearchWithHHmm('s_create_time', 's_create_time_begin', 's_create_time_end');
                SYS.Tool.initDaterangSearchWithHHmm('s_last_time', 's_last_time_begin', 's_last_time_end');


                //批量删除
                $("#btn_deletes").on('click',function(){
                    that.toRemoves();
                });

                // 绑定日期控件
                $("#creaetdate, #lastlogin").datetimepicker({
                    minView: "hour",
                    format: 'yyyy-mm-dd hh:ii',
                    todayBtn: true,
                    language: 'zh-CN', // 汉化
                    autoclose: true    // 选择日期后自动关闭
                }).on('changeDate', function (ev) {
                    var field = $(this).attr("id");
                    $form.find("input[data-field='" + field + "']").val(ev.date.getTime());
                });

                // 保存新增
                $("#btn_contiune_add").on('click', function () {
                    // 不用关闭当前编辑框
                    that.save(1);
                });

                // 新增
                $("#btn_add").on('click', function () {
                    that.clearDatas();
                    // 初始化图片组件
                    that.initFileinput();

                    $("#btn-add-div").show();
                    $("#btn-edit-div").hide();
                    that.showDiv('edit_div');
                });

                $("#btn_export").on('click', function () {
                    that.toExport();
                });

                $(".i-checks").iCheck({checkboxClass:"icheckbox_square-orange", radioClass:"iradio_square-orange"});
                $("#btn_import").on('click', function () {

                    $("#import_tip").html('');
                    $("#import_file").fileinput('refresh', {
                        uploadUrl: '/base/airecord/importData?',
                        showUploadedThumbs: false,
                        browseClass: 'btn btn-main',
                        allowedFileExtensions: ["xls", "xlsx"],
                        uploadExtraData: function(previewId, index) {   //额外参数的关键点
                            var obj = {};
                            obj.parameters = BASE.airecord.fodderType();
                            console.log(obj);
                            return obj;
                        }
                    }).on('fileuploaded', function (event, data) {
                        var data = data.response;
                        $("#import_tip").html(data.msg);
                    });

                    that.showDiv('import_div');
                });

                // 返回
                $(".back_list").on('click', function () {
                    that.clearDatas();
                    that.showDiv('main_div');
                });

                //
                $('#fm').bootstrapValidator({
                    excluded: ':disabled',
                    feedbackIcons: {
                        valid: 'glyphicon glyphicon-ok',
                        invalid: 'glyphicon glyphicon-remove',
                        validating: 'glyphicon glyphicon-refresh'
                    },
                    fields: {
                        // title: {
                        //     validators: {
                        //         notEmpty: {
                        //             message: '此项必填'
                        //         }
                        //     }
                        // },
                        // order: {
                        //     validators: {
                        //         notEmpty: {
                        //             message: '此项必填'
                        //         },
                        //         regexp: {
                        //             regexp: /^[1-9]\d*$/i,
                        //             message: '格式不正确，必须大于0'
                        //         }
                        //     }
                        // }
                    }
                }).on('success.form.bv', function (e) {
                    e.preventDefault();

                    that.save(0);
                });

            },
            fodderType(){
              return JSON.stringify({
                    common:{},
                    data: {
                        flag: $("input[name='free_trial']:checked").val()
                    }
                });
            },
            save: function (isContinus) {
                var that = this;

                var id = $("#_id").val();
                var title = $("#title").val();
                var searchkey = $("#searchkey").val();
                var info = ueditor.getContent();

                SYS.Core.ajax({
                    url: 'base/airecord/save',
                    common: {},
                    data:{
                        id: id || 0,
                        title: title,
                        searchkey: searchkey,
                        info: info,
                    },
                    success: function (data) {
                        if(data.code == 1) {
                            $.messager.popup(data.msg, 'success');

                            if (isContinus) {
                                that.clearDatas();
                                that.loadData();
                                that.showDiv('edit_div');
                            } else {
                                that.loadData();
                                that.showDiv('main_div');
                            }

                        } else {
                            $('#fm').bootstrapValidator('disableSubmitButtons', false);
                            $.messager.popup(data.msg, 'error');
                        }
                    }
                })
            },
            toEdit: function (id) {
                var that = this;
                that.clearDatas();
                $("#btn-add-div").hide();
                $("#btn-edit-div").show();

                SYS.Core.ajax({
                    url: 'base/airecord/detail',
                    common: {},
                    data: {
                        id: id ? id : 0
                    },
                    success: function (data) {
                        if (data.code == 1) {
                            var obj = data.data;
                            const id = obj.id;
                            const title = obj.title;
                            const searchkey = obj.searchkey;
                            const info = obj.info;

                            $("#_id").val(id);
                            $("#title").val(title);
                            $("#searchkey").val(searchkey);
                            // $("#info").val(info);
                            var ue = ueditor;
                            ue.setContent("");
                            ue.setContent(info ? info : "");

                            that.showDiv('edit_div');
                        }
                    }
                });
            },
            toRemove: function (id) {
                var that = this;
                $.messager.confirm("确定要删除吗？", function() {
                    SYS.Core.ajax({
                        url: "base/airecord/delete",
                        common: {},
                        data: {
                            ids: [id]
                        },
                        success: function (data) {
                            if(data.code == 1){
                                $.messager.popup(data.msg, "success");
                                that.loadData();
                            }else{
                                $.messager.popup(data.msg,'error');
                            }
                        }
                    })
                });
            },
            toRemoves: function () {
                var that = this;
                var selRows = $('#myTable').bootstrapTable('getSelections');
                var delIds = [];
                if(selRows.length > 0){
                    $.each(selRows, function (i, obj) {
                        if(obj.id > 0){
                            delIds.push(obj.id);
                        }
                    });
                    $.messager.confirm("确定批量删除吗？", function() {
                        SYS.Core.ajax({
                            url: "base/airecord/delete",
                            common: {},
                            data: {
                                ids: delIds
                            },
                            success: function (data) {
                                if(data.code == 1){
                                    $.messager.popup(data.msg,"success");
                                    that.loadData();
                                }else{
                                    $.messager.popup(data.msg,'error');
                                }
                            }
                        })
                    });
                }else{
                    $.messager.popup('请选择一条记录后再删除','warn');
                }
            },
            initFileinput: function (initialPreview) {
                var options = {
                    img_id: 'img',
                    type_id: 5000,
                    initialPreview: initialPreview,
                    hid_img_id: 'hide_img',
                    showZoom: false
                };
                SYS.Tool.initSingleImg(options);
            },
            initUEditor: function () {
                var ue = UE.getEditor('info');
                UE.Editor.prototype._bkGetActionUrl = UE.Editor.prototype.getActionUrl;
                UE.Editor.prototype.getActionUrl = function (action) {
                    if (action == 'uploadimage' || action == 'uploadscrawl') {
                        return '/picture/uploadByUE/3000';
                    } else {
                        return this._bkGetActionUrl.call(this, action);
                    }
                };
                ueditor = ue;
            },
            toExport: function () {
                var that = this;

                var s_id = $("#s_id").val();
                var s_title = $("#s_title").val();
                var s_searchkey = $("#s_searchkey").val();
                var s_info = $("#s_username").val();

                var data = {
                    id: s_id || 0,
                    title: s_title,
                    searchkey: s_searchkey,
                    info: s_info
                };

                var parameters = JSON.stringify({
                    common:{},
                    data: data
                });

                $.messager.confirm('确定要导出吗？', function () {
                    window.open( '/base/airecord/exportData?parameters=' + encodeURI(parameters));
                });
            },
            showDiv: function (div) {
                var divs = ['main_div','edit_div','import_div'];
                for(var i=0; i<divs.length; i++){
                    $("#" + divs[i]).hide();
                }
                $("#" + div).show();
            }
        }
    });
    BASE.airecord.init();
});